/**
 * 驰声模块
 */
var chivoxLongman;
// 初始化引擎
function initEngine() {
    function callback() {
        chivoxLongman = api.require('chivoxLongman');
        chivoxLongman.initEngine({
            appKey:'1555570547000002',
            secretKey:'abb3d5cb19a6de39b3f86e3f0a5fecd0',
            provisionPath:'widget://res/aiengine.provision',
            vadPath: 'fs://vad.bin',
            serverPath:'wss://cloud.chivox.com:443'
        },function(ret, err){
            if(ret.status){
                console.log('声通引擎初始化成功');
            }else {
                var msg = JSON.stringify(ret) +'====='+ JSON.stringify(err)
                console.error('声通初始化失败：==>'+msg);
            }
        });
    }
    var fs = api.require('fs');
    fs.createDir({
        path: 'fs://chivox'
    }, function(ret, err) {
        
    });
    var resultList = api.hasPermission({
        list: ['microphone']
    });
    if (!resultList[0]['granted']) {
        api.requestPermission({
            list: ['microphone']
        }, function(ret) {
            if (ret && ret.list) {
                if (!ret.list[0]['granted']) {
                    fnToast('您没有允许录音权限，请允许后继续');
                }else {
                    callback();
                }
            }
        })
    } else {
        callback();
    }
    
}
    
var start = false;
// 单词语音识别
function fnWordRecordIdentify(word, callback) {
    if(!chivoxLongman) {
        initEngine();
        var params = {
            url: '',
            localPath: '',
            score: 0
        }
        callback(params);
        return;
    }
    if(start) {
        console.info(new Date().getTime()+'end-start');
        chivoxLongman.stopRecord();
        return;
    }
    start = true;
    console.info(new Date().getTime()+'start'+word);
    var androidSavePath = '/langwen' + new Date().getTime() + '.wav';
    var params = {};
    if(api.systemType == 'ios') {
        params = { 
            savePath: 'fs://chivox/',
            userId: 'test',
            coreProvideType: 'cloud',
            audioType: 'wav',
            sampleRate: 16000,
            sampleBytes: 2,
            refText: word,
            coreType: 'en.word.score',
            rank: 100,
            attachAudioUrl: 1,
            channel: 1,
            vadRefDuration: 1
        }
    }else {
        console.log(androidSavePath +'---->androidSavePath');
        params = { 
            androidSavePath: 'fs:/' + androidSavePath,
            userId: 'test',
            coreProvideType: 'cloud',
            channel: 1,
            vadRefDuration: 0,
            request: {
                coreType: 'en.word.score',
                refText: word,
                attachAudioUrl: 1,
                rank: 100
            }
        }
    }
    console.log(JSON.stringify(params) +'---->android参数');
    chivoxLongman.startRecord(params, function(ret,err){
        console.log('chivoxLongman.startRecord======callback');
        if (ret.status) {
            var msg = JSON.stringify(ret);
            console.log('111111==='+msg);
            var responseData = ret.responseData;
            if(typeof responseData === 'string') {
                responseData = JSON.parse(responseData);
            }
            if(responseData.vad_status == 2) {
                fnStopRecord();
            }else if(responseData.result) {
                var data = responseData.result;
                var realPath = ret.realPath;
                if(api.systemType == 'ios') {
                    realPath = '/chivox' + realPath.split('chivox')[1];
                }else {
                    realPath = androidSavePath;
                }
                var audioUrl = responseData.audioUrl || '';
                var params = {
                    url: 'http://'+ audioUrl +'.mp3', // Android没有此返回数据
                    localPath: realPath,
                    score: data.overall
                };
                callback(params);
                start = false;
            }
        } else {
            var msg = JSON.stringify(err);
            console.error(word +'单词识别错误：'+ msg);
            start = false;
        }
    });
}

// 停止录音
function fnStopRecord() {
    console.info(new Date().getTime()+'end');
    chivoxLongman.stopRecord();
}

var sentChanger = {
    'FEB 26': "It's the twenty-sixth of February",
    '23.01.15': 'twenty third of January',
    '31 August': 'thirty first of August',
    '02/06/14': 'the second of June',
    'Monday，30 October 2014': 'the thirtieth of October',
    '9 Sept 2014 Fri': 'the ninth of September',
    "It's the twenty-sixth of February.": "It's the twenty-sixth of February.",
};
// 句子语音识别
function fnSentRecordIdentify(sent, callback) {
    var change = sentChanger[sent];
    sent = change || sent; 
    if(!chivoxLongman) {
        initEngine();
        var params = {
            url: '',
            localPath: '',
            score: 0
        }
        callback(params);
        return;
    }
    if(start) {
        chivoxLongman.stopRecord();
        return;
    }
    start = true;
    console.log('star-with-'+ sent);
    var androidSavePath = '/langwen' + new Date().getTime() + '.wav';
    var params = {};
    if(api.systemType == 'ios') {
        params = { 
            savePath: 'fs://chivox/',
            userId: 'test',
            coreProvideType: 'cloud',
            audioType: 'wav',
            sampleRate: 16000,
            sampleBytes: 2,
            refText: sent,
            coreType: 'en.sent.score',
            rank: 100,
            attachAudioUrl: 1,
            channel: 1,
            vadRefDuration: 1,
        }
    }else {
        console.log(androidSavePath +'---->androidSavePath');
        params = { 
            androidSavePath: 'fs:/' + androidSavePath,
            userId: 'test',
            coreProvideType: 'cloud',
            channel: 1,
            vadRefDuration: 0,
            request: {
                coreType: 'en.word.score',
                refText: sent,
                attachAudioUrl: 1,
                rank: 100
            }
        };
    }
    chivoxLongman.startRecord(params, function(ret,err){
        console.log('chivoxLongman.startRecord======callback====='+JSON.stringify(ret));
        if (ret.status) {
            var msg = JSON.stringify(ret);
            console.log('111111==='+msg);
            var responseData = ret.responseData;
            if(typeof responseData === 'string') {
                responseData = JSON.parse(responseData);
            }
            if(responseData.vad_status == 2) {
                fnStopRecord();
            }else if(responseData.result) {
                var data = responseData.result;
                var realPath = ret.realPath;
                if(api.systemType == 'ios') {
                    realPath = '/chivox' + realPath.split('chivox')[1];
                }else {
                    realPath = androidSavePath;
                }
                var audioUrl = responseData.audioUrl || '';
                var params = {
                    url: 'http://'+audioUrl+'.mp3',
                    localPath: realPath,
                    score: data.overall,
                    details: data.details // listmap,map中的score为每个单词得分
                };
                callback(params);
                start = false;
            }
        } else {
            var msg = JSON.stringify(err);
            console.error(sent +'句子识别错误：'+ msg);
            start = false;
        }
    });
}